import axios from 'axios'

const service = axios.create({ timeout: 30000 })

// 请求拦截器
service.interceptors.request.use(
  (conf) => {
    conf.headers.token = localStorage.getItem("token")
    return conf
  },
  (err) => {
    return Promise.reject(new Error(err))
  }
)

//响应拦截器
service.interceptors.response.use(
  res => {
    if(res && res.data) {
      return Promise.resolve(res.data)
    } else {
      return Promise.resolve({code: '1010', msg: '系统错误，请联系系统管理员。'})
    }
  },
  err => {
    if(err && err.data) {
      return Promise.reject(new Error(err.data.msg))
    } else if(err.code==='ERR_NETWORK' || err.message==='Network Error' || err.message.indexOf('timeout')!==-1) {
      return Promise.resolve({code: '1011', msg: '网络断开或连接超时，请检查。'})
    } else {
      return Promise.resolve({code: '1012', msg: '请求响应错误，请联系系统管理员。'})
    }
  }
)

export default service
